// 项目合作归属数据管理系统前端脚本

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能
    initDataTables();
    initDatePickers();
    initFormValidation();
    initTooltips();
    initModals();
    initFileUpload();
    initSearchFilters();
});

// 初始化数据表格
function initDataTables() {
    const tables = document.querySelectorAll('.data-table');
    tables.forEach(table => {
        // 如果表格有分页，添加分页功能
        if (table.classList.contains('paginated')) {
            addPagination(table);
        }
        
        // 添加排序功能
        addSorting(table);
        
        // 添加搜索功能
        addTableSearch(table);
    });
}

// 初始化日期选择器
function initDatePickers() {
    const dateInputs = document.querySelectorAll('input[type="date"], input[type="datetime-local"]');
    dateInputs.forEach(input => {
        // 设置默认日期格式和限制
        if (input.type === 'date') {
            input.style.fontFamily = 'inherit';
        }
        
        // 添加验证
        input.addEventListener('change', function() {
            validateDateInput(this);
        });
    });
}

// 初始化表单验证
function initFormValidation() {
    const forms = document.querySelectorAll('form[data-validate="true"]');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!validateForm(this)) {
                e.preventDefault();
            }
        });
    });
}

// 初始化工具提示
function initTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

// 初始化模态框
function initModals() {
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
        modal.addEventListener('hidden.bs.modal', function() {
            // 清空表单
            const forms = this.querySelectorAll('form');
            forms.forEach(form => form.reset());
        });
    });
}

// 初始化文件上传
function initFileUpload() {
    const fileInputs = document.querySelectorAll('input[type="file"]');
    fileInputs.forEach(input => {
        input.addEventListener('change', function() {
            handleFileUpload(this);
        });
    });
}

// 初始化搜索过滤器
function initSearchFilters() {
    const searchForms = document.querySelectorAll('.search-form');
    searchForms.forEach(form => {
        const inputs = form.querySelectorAll('input, select');
        inputs.forEach(input => {
            input.addEventListener('input', debounce(function() {
                if (form.dataset.autoSubmit === 'true') {
                    form.submit();
                }
            }, 500));
        });
    });
}

// 表单验证函数
function validateForm(form) {
    let isValid = true;
    const requiredFields = form.querySelectorAll('[required]');
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            showFieldError(field, '此字段为必填项');
            isValid = false;
        } else {
            clearFieldError(field);
        }
    });
    
    // 特殊验证
    const emailFields = form.querySelectorAll('input[type="email"]');
    emailFields.forEach(field => {
        if (field.value && !isValidEmail(field.value)) {
            showFieldError(field, '请输入有效的邮箱地址');
            isValid = false;
        }
    });
    
    const phoneFields = form.querySelectorAll('input[data-type="phone"]');
    phoneFields.forEach(field => {
        if (field.value && !isValidPhone(field.value)) {
            showFieldError(field, '请输入有效的手机号码');
            isValid = false;
        }
    });
    
    return isValid;
}

// 显示字段错误
function showFieldError(field, message) {
    clearFieldError(field);
    
    field.classList.add('is-invalid');
    const errorDiv = document.createElement('div');
    errorDiv.className = 'invalid-feedback';
    errorDiv.textContent = message;
    field.parentNode.appendChild(errorDiv);
}

// 清除字段错误
function clearFieldError(field) {
    field.classList.remove('is-invalid');
    const errorDiv = field.parentNode.querySelector('.invalid-feedback');
    if (errorDiv) {
        errorDiv.remove();
    }
}

// 验证邮箱格式
function isValidEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

// 验证手机号格式
function isValidPhone(phone) {
    const re = /^1[3-9]\d{9}$/;
    return re.test(phone);
}

// 日期输入验证
function validateDateInput(input) {
    const value = input.value;
    if (!value) return;
    
    const date = new Date(value);
    const now = new Date();
    
    if (input.dataset.maxDate === 'today' && date > now) {
        showFieldError(input, '日期不能超过今天');
    } else if (input.dataset.minDate === 'today' && date < now) {
        showFieldError(input, '日期不能早于今天');
    } else {
        clearFieldError(input);
    }
}

// 文件上传处理
function handleFileUpload(input) {
    const file = input.files[0];
    if (!file) return;
    
    // 检查文件大小
    const maxSize = input.dataset.maxSize || 16 * 1024 * 1024; // 16MB
    if (file.size > maxSize) {
        alert('文件大小不能超过 ' + (maxSize / 1024 / 1024) + 'MB');
        input.value = '';
        return;
    }
    
    // 检查文件类型
    const allowedTypes = input.dataset.allowedTypes;
    if (allowedTypes) {
        const types = allowedTypes.split(',');
        const fileExtension = file.name.split('.').pop().toLowerCase();
        if (!types.includes(fileExtension)) {
            alert('只允许上传以下类型的文件: ' + allowedTypes);
            input.value = '';
            return;
        }
    }
    
    // 显示文件信息
    const fileInfo = input.parentNode.querySelector('.file-info');
    if (fileInfo) {
        fileInfo.textContent = `已选择: ${file.name} (${formatFileSize(file.size)})`;
    }
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 表格排序
function addSorting(table) {
    const headers = table.querySelectorAll('th[data-sortable="true"]');
    headers.forEach(header => {
        header.style.cursor = 'pointer';
        header.addEventListener('click', function() {
            sortTable(table, this);
        });
    });
}

// 排序表格
function sortTable(table, header) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const headerIndex = Array.from(header.parentNode.children).indexOf(header);
    const isAscending = header.classList.contains('sort-asc');
    
    rows.sort((a, b) => {
        const aValue = a.children[headerIndex].textContent.trim();
        const bValue = b.children[headerIndex].textContent.trim();
        
        // 数字排序
        if (!isNaN(aValue) && !isNaN(bValue)) {
            return isAscending ? bValue - aValue : aValue - bValue;
        }
        
        // 文本排序
        return isAscending ? 
            bValue.localeCompare(aValue, 'zh-CN') : 
            aValue.localeCompare(bValue, 'zh-CN');
    });
    
    // 清除所有排序类
    table.querySelectorAll('th').forEach(th => {
        th.classList.remove('sort-asc', 'sort-desc');
    });
    
    // 添加当前排序类
    header.classList.add(isAscending ? 'sort-desc' : 'sort-asc');
    
    // 重新排列行
    rows.forEach(row => tbody.appendChild(row));
}

// 表格搜索
function addTableSearch(table) {
    const searchInput = document.querySelector(`[data-table-search="${table.id}"]`);
    if (!searchInput) return;
    
    searchInput.addEventListener('input', debounce(function() {
        const searchTerm = this.value.toLowerCase();
        const rows = table.querySelectorAll('tbody tr');
        
        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(searchTerm) ? '' : 'none';
        });
    }, 300));
}

// 分页功能
function addPagination(table) {
    const rowsPerPage = parseInt(table.dataset.rowsPerPage) || 10;
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const totalPages = Math.ceil(rows.length / rowsPerPage);
    
    if (totalPages <= 1) return;
    
    // 创建分页容器
    const paginationContainer = document.createElement('nav');
    paginationContainer.className = 'mt-3';
    paginationContainer.innerHTML = `
        <ul class="pagination justify-content-center">
            <li class="page-item">
                <a class="page-link" href="#" data-page="prev">上一页</a>
            </li>
            ${Array.from({length: totalPages}, (_, i) => `
                <li class="page-item ${i === 0 ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i + 1}">${i + 1}</a>
                </li>
            `).join('')}
            <li class="page-item">
                <a class="page-link" href="#" data-page="next">下一页</a>
            </li>
        </ul>
    `;
    
    table.parentNode.appendChild(paginationContainer);
    
    // 显示第一页
    showPage(1, rows, rowsPerPage);
    
    // 绑定分页事件
    paginationContainer.addEventListener('click', function(e) {
        e.preventDefault();
        if (e.target.classList.contains('page-link')) {
            const page = e.target.dataset.page;
            const currentPage = parseInt(paginationContainer.querySelector('.page-item.active .page-link').dataset.page);
            
            let newPage;
            if (page === 'prev') {
                newPage = Math.max(1, currentPage - 1);
            } else if (page === 'next') {
                newPage = Math.min(totalPages, currentPage + 1);
            } else {
                newPage = parseInt(page);
            }
            
            if (newPage !== currentPage) {
                showPage(newPage, rows, rowsPerPage);
                updatePaginationActive(paginationContainer, newPage);
            }
        }
    });
}

// 显示指定页面
function showPage(page, rows, rowsPerPage) {
    const start = (page - 1) * rowsPerPage;
    const end = start + rowsPerPage;
    
    rows.forEach((row, index) => {
        row.style.display = (index >= start && index < end) ? '' : 'none';
    });
}

// 更新分页活动状态
function updatePaginationActive(container, page) {
    container.querySelectorAll('.page-item').forEach(item => {
        item.classList.remove('active');
    });
    
    const pageLink = container.querySelector(`[data-page="${page}"]`);
    if (pageLink) {
        pageLink.parentNode.classList.add('active');
    }
}

// AJAX请求封装
function ajaxRequest(url, options = {}) {
    const defaults = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    };
    
    const config = Object.assign(defaults, options);
    
    return fetch(url, config)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .catch(error => {
            console.error('Ajax request failed:', error);
            throw error;
        });
}

// 显示加载状态
function showLoading(element) {
    const spinner = document.createElement('div');
    spinner.className = 'text-center';
    spinner.innerHTML = `
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
    `;
    element.appendChild(spinner);
}

// 隐藏加载状态
function hideLoading(element) {
    const spinner = element.querySelector('.spinner-border');
    if (spinner) {
        spinner.parentNode.remove();
    }
}

// 显示成功消息
function showSuccess(message) {
    showAlert(message, 'success');
}

// 显示错误消息
function showError(message) {
    showAlert(message, 'danger');
}

// 显示警告消息
function showWarning(message) {
    showAlert(message, 'warning');
}

// 显示提示消息
function showAlert(message, type = 'info') {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = `
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
    `;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 自动移除
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}

// 确认对话框
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}

// 导出功能
function exportData(url, filename) {
    showLoading(document.body);
    
    fetch(url)
        .then(response => response.blob())
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        })
        .catch(error => {
            showError('导出失败: ' + error.message);
        })
        .finally(() => {
            hideLoading(document.body);
        });
}

// 批量操作
function batchOperation(operation, selectedItems) {
    if (selectedItems.length === 0) {
        showWarning('请选择要操作的项目');
        return;
    }
    
    const message = `确定要${operation} ${selectedItems.length} 个项目吗？`;
    confirmAction(message, () => {
        // 执行批量操作
        ajaxRequest('/api/batch_operation', {
            method: 'POST',
            body: JSON.stringify({
                operation: operation,
                items: selectedItems
            })
        }).then(result => {
            if (result.success) {
                showSuccess('操作成功');
                location.reload();
            } else {
                showError('操作失败: ' + result.message);
            }
        });
    });
}

// 全选/取消全选 - 全局函数
window.toggleSelectAll = function(checkbox) {
    console.log('toggleSelectAll called, checkbox checked:', checkbox.checked);
    const checkboxes = document.querySelectorAll('input[type="checkbox"][name="selected_items"]');
    console.log('Found checkboxes:', checkboxes.length);
    
    checkboxes.forEach(cb => {
        cb.checked = checkbox.checked;
    });
    
    updateBatchButtons();
};

// 更新批量操作按钮状态 - 全局函数  
window.updateBatchButtons = function() {
    const checkedBoxes = document.querySelectorAll('input[type="checkbox"][name="selected_items"]:checked');
    const batchButtons = document.querySelectorAll('.batch-operation-btn');
    
    console.log('updateBatchButtons called - checked boxes:', checkedBoxes.length, 'batch buttons found:', batchButtons.length);
    
    batchButtons.forEach(btn => {
        console.log('Updating button:', btn, 'disabled:', checkedBoxes.length === 0);
        btn.disabled = checkedBoxes.length === 0;
        
        if (checkedBoxes.length === 0) {
            btn.classList.add('disabled');
            btn.setAttribute('disabled', 'disabled');
        } else {
            btn.classList.remove('disabled');
            btn.removeAttribute('disabled');
        }
    });
};

